<html>
    <head>
    	<link type="text/css" rel="stylesheet" href="lib/beauty.css" />
    	<script type="text/javascript" src="lib/AIRAliases.js"></script>
		<link rel="stylesheet" type="text/css" href="lib/nifty/niftyCorners.css">
		<link rel="stylesheet" type="text/css" href="lib/nifty/niftyPrint.css" media="print">
		<script type="text/javascript" src="lib/nifty/nifty.js"></script>
		<script src="lib/progbar.js" type="text/javascript"></script>
		<script type="text/javascript">
			function starttime() {
				var iconLoadComplete = function(event)
			    {
			        air.NativeApplication.nativeApplication.icon.bitmaps = new runtime.Array(event.target.content.bitmapData);
			    }
				var iconLoad = new air.Loader();
				var iconMenu = new air.NativeMenu();
				var close = new air.NativeMenuItem("Close", false);
				close.addEventListener(air.Event.SELECT, closeMainWindow);
				iconMenu.addItem(close);
			    if (air.NativeApplication.supportsSystemTrayIcon) {
			        air.NativeApplication.nativeApplication.autoExit = true;
			        iconLoad.contentLoaderInfo.addEventListener(air.Event.COMPLETE,iconLoadComplete);
			        iconLoad.load(new air.URLRequest("icons/AIRApp_16.png"));
			        air.NativeApplication.nativeApplication.icon.tooltip = "Skylight";
			        air.NativeApplication.nativeApplication.icon.menu = iconMenu;
			    }
			
			    if (air.NativeApplication.supportsDockIcon) {
			        iconLoad.contentLoaderInfo.addEventListener(air.Event.COMPLETE,iconLoadComplete);
			        iconLoad.load(new air.URLRequest("icons/AIRApp_128.png"));
			        air.NativeApplication.nativeApplication.icon.menu = iconMenu;
			    }
			}
			function closeMainWindow() {
				nativeWindow.close();
			}
			function pageViaForm() {
				myProgBar.setBar(0);
				document.getElementById('hiploader').style.display = 'block';
				document.getElementById('loaderror').style.display = 'none';
				myProgBar.setBar(0.2,true);
				var place = document.changeform.pickyplaces.value;
				document.getElementById('extras').style.display = 'none';
				document.changeform.change.disabled = true;
				document.getElementById('ftop').innerHTML = "";
				document.getElementById('fbottom').innerHTML = "";
				document.getElementById('pickplace').innerHTML = "";
				document.getElementById('longcast').innerHTML = "";
				document.getElementById('warnbox').innerHTML = "";
				document.getElementById('curbox').innerHTML = ""; 
				cordRet(place);
			}
			function loadPagePrefs() {
				var preflocation;
				prefsFile = air.File.applicationStorageDirectory;
				prefsFile = prefsFile.resolvePath("preferences.xml");
				stream = new air.FileStream();
				if (prefsFile.exists) {
					stream.open(prefsFile, air.FileMode.READ);
					prefsXML = stream.readUTFBytes(stream.bytesAvailable);
					stream.close();
					var domParser = new DOMParser();
					prefsXML = domParser.parseFromString(prefsXML, "text/xml");
					var defLoc = prefsXML.getElementsByTagName("defaultLocation")[0];
					var lats = defLoc.getAttribute("lat");
					var longs = defLoc.getAttribute("long");
					var place = defLoc.getAttribute("place");
					ajaxLoader(lats,longs,place);
				} else {
					cordRet(preflocation);
				}
				return preflocation;
			}
			function saveDefaultLocation() {
				var lats = document.latlong.lats.value;
				var longs = document.latlong.longs.value;
				var place = document.latlong.place.value;
				place = place.replace("'","")
				var cr = air.File.lineEnding;
				var prefsXML =   "<?xml version='1.0' encoding='utf-8'?>" + cr
								+ "<preferences>" + cr 
								+ "    <defaultLocation" + cr
								+ "  		place = '" + place + "'" + cr
								+ " 		lat = '" + lats + "'" + cr
								+ "			long = '" + longs + "' />" + cr
								+ "    <saveDate>"
								+            new Date().toString() 
								+     "</saveDate>" + cr
								+ "</preferences>";
				stream = new air.FileStream();
				stream.open(prefsFile, air.FileMode.WRITE);
				stream.writeUTFBytes(prefsXML);
				stream.close();
			}
			var state = 'none';
			function cordRet(forelocation)
			{
				
				if (document.getElementById) {
					var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
					}
					if (x)
						{
					x.onreadystatechange = function()
							{
						if (x.readyState == 3)
								{
								document.changeform.change.disabled = true;
								document.getElementById('hiploader').style.display = 'block';
								}
						if (x.readyState == 4 && x.status == 404)
								{
								document.changeform.change.disabled = false;
								document.getElementById('welcomescreen').style.display = 'none';
								document.getElementById('hiploader').style.display = 'none';
								document.getElementById('loaderror').style.display = 'block';
								}	
						if (x.readyState == 4 && x.status == 200)
								{
								document.getElementById('hiploader').style.display = 'block';
								myProgBar.setBar(0.2,true);
								var locstring;
								var response = x.responseXML;
								if (response.getElementsByTagName('latitude')[0].hasChildNodes()) { 
									var place = response.getElementsByTagName('place')[0].firstChild.data;
									var flat = response.getElementsByTagName('latitude')[0].firstChild.data;
									var flong = response.getElementsByTagName('longitude')[0].firstChild.data;
									document.latlong.lats.value = flat;
									document.latlong.longs.value = flong;
									document.latlong.place.value = place;
									ajaxLoader(flat,flong,place);
								} else {
									document.getElementById('hiploader').style.display = 'none';
									var elem = document.createElement("td");
									elem.setAttribute("align", "center");
									elem.innerHTML = "Invalid Location! Please try a different location.";
									document.changeform.change.disabled = false;
									document.getElementById('ftop').appendChild(elem);
								}
								myProgBar.setBar(0.4,true);
							}
							}
						if (forelocation === undefined) {
    						forelocation = "Salt Lake City, Utah";
  						}
						var url = "http://www.dontfooleveryone.com/skylight/georequest.php?location=" + forelocation;
						x.open("GET", url, true);
						x.send(null);
						
						}
						
			    }
			
		   function ajaxLoader(picklat,picklong,place)
			{
				
				if (document.getElementById) {
					var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
					}
					if (x)
						{
					x.onreadystatechange = function()
							{
						if (x.readyState == 3)
								{
								document.getElementById('hiploader').style.display = 'block';
								myProgBar.setBar(0.5,true);
								}
						if (x.readyState == 4 && x.status == 404)
								{
								document.getElementById('welcomescreen').style.display = 'none';
								document.changeform.change.disabled = false;
								document.getElementById('hiploader').style.display = 'none';
								document.getElementById('loaderror').style.display = 'block';
								}		
						if (x.readyState == 4 && x.status == 200)
								{
								document.getElementById('hiploader').style.display = 'block';
								myProgBar.setBar(0.6,true);
								var forehead = [];
								var dows = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
								var forestring = [];
								var forebase = [];
								var warnables = [];
								var currents = [];
								var response = x.responseXML;
								var elem = document.createElement("span");
								elem.innerHTML = "<strong>" + place + "</strong>";
								document.getElementById('hiploader').style.display = 'none';
								document.getElementById('welcomescreen').style.display = 'none';
								document.getElementById('extras').style.display = 'block';
								document.changeform.change.disabled = false;
								document.getElementById('pickplace').appendChild(elem);
								var foreNode = response.getElementsByTagName('Forecast')[0];
								var iconable = foreNode.getElementsByTagName('icon-location')[0].firstChild.data;
								var rootNode = foreNode.getElementsByTagName('period');
								myProgBar.setBar(0.7,true);
								for (var i = 0; i < rootNode.length; i++ ) {
									var valid = rootNode[i].getElementsByTagName('valid')[0].firstChild.data;
									var image = rootNode[i].getElementsByTagName('image')[0].firstChild.data;
									var weather = rootNode[i].getElementsByTagName('weather')[0].firstChild.data;
									var temp = rootNode[i].getElementsByTagName('temp')[0].firstChild.data;
									var ttype = rootNode[i].getElementsByTagName('temp')[0].getAttribute("hilo");
									var ftext = rootNode[i].getElementsByTagName('text')[0].firstChild.data;
									if (ttype == "H") { ttype = "High: ";} else { ttype = "Low: ";}
									forehead[i] = "<strong>" + valid + "</strong>"
									forestring[i] = "<img src=\"" + iconable + "/" + image + "\" border=\"0\"><br />" + weather + "<br />" + ttype + temp;
									forebase[i] = "<strong>" + valid + "</strong><br />" + ftext;
								}
								myProgBar.setBar(0.8,true);
								var warnNode = response.getElementsByTagName('products')[0];
								var rootWarn = warnNode.getElementsByTagName('product');
								for (var i = 0; i < rootWarn.length; i++ ) {
									var valid = rootWarn[i].getElementsByTagName('haz_end')[0].firstChild.data;
									var type = rootWarn[i].getElementsByTagName('prod_type')[0].firstChild.data;
									var text = rootWarn[i].getElementsByTagName('text')[0].firstChild.data;
									var unixDate = new Date(valid * 1000);
									var day = unixDate.getDay();
									var hour = unixDate.getHours();
									if (hour > 12) {
										hour = hour - 12;
										var dset = "PM";
									} else {
										var dset = "AM";
									}
									var min = unixDate.getMinutes();
									if (min < 10) {
										min = "00";
									}
									var dateString = unixDate.toLocaleString();
									warnables[i] = "<div>" + type + "</div><div><i>Expires at " + hour + ":" + min + dset + " on " + dows[day] + "</i></div>";
								}
								var curNode = response.getElementsByTagName('mesonet')[0];
								var rootCur = curNode.getElementsByTagName('station');
								for (var i = 0; i < 1; i++ ) {
									var curname = rootCur[i].getAttribute("name");
									var obBlock = rootCur[i].getElementsByTagName('ob');
									var varBlock = rootCur[i].getElementsByTagName('variable');
									var temp = "NA"; var rh = "NA"; var wspd = "0"; var wdir = "NA"; var weather = "Not Availible";
									for (var j = 0; j < varBlock.length; j++ ) {
										var varcheck = varBlock[j].getAttribute("var");
										if (varcheck == "RH") {
											rh = varBlock[j].getAttribute("value");
										}
										if (varcheck == "T") {
											temp = varBlock[j].getAttribute("value");
										}
										if (varcheck == "FF") {
											wspd = varBlock[j].getAttribute("value");
										}
										if (varcheck == "DDCARD") {
											wdir = varBlock[j].getAttribute("value");
										}
										if (varcheck == "WEA") {
											weather = varBlock[j].getAttribute("value");
										}
									}
									if (wdir == "CALM") {
									currents[i] = curname + "<table width=\"75%\"><tr><td align=\"center\" colspan=\"2\">" + weather + "</td></tr><tr><td align=\"right\">Temp: <td align=\"left\">" + temp + "&deg;F</td></tr><tr><td align=\"right\">RH: <td align=\"left\">" + rh + "%</td></tr><tr><td align=\"right\">Wind: <td align=\"left\">" + wdir + "</td></tr></table>";	
									} else {
									currents[i] = curname + "<table width=\"75%\"><tr><td align=\"center\" colspan=\"2\">" + weather + "</td></tr><tr><td align=\"right\">Temp: <td align=\"left\">" + temp + "&deg;F</td></tr><tr><td align=\"right\">RH: <td align=\"left\">" + rh + "%</td></tr><tr><td align=\"right\">Wind: <td align=\"left\">" + wdir + " @ " + wspd + "mph</td></tr></table>";
									}
								}
								myProgBar.setBar(0.9,true);
									for (var i = 0; i < forestring.length - 4; i++ ) {
										var elem = document.createElement("td");
										elem.setAttribute("align", "center");
										elem.setAttribute("valign", "center");
										elem.setAttribute("width", "11%");
										elem.innerHTML = forehead[i];
										document.getElementById('ftop').appendChild(elem);
									}
									for (var i = 0; i < forestring.length - 4; i++ ) {
										var elem = document.createElement("td");
										elem.setAttribute("align", "center");
										elem.setAttribute("valign", "top");
										elem.setAttribute("width", "11%");
										elem.innerHTML = forestring[i];
										document.getElementById('fbottom').appendChild(elem);
									}
									for (var i = 0; i < forestring.length - 4; i++ ) {
										var elem = document.createElement("div");
										elem.setAttribute("style", "padding-bottom:6px;");
										elem.innerHTML = forebase[i];
										document.getElementById('longcast').appendChild(elem);
									}
									var elem = document.createElement("div");
									elem.setAttribute("align", "center");
									elem.setAttribute("style", "padding-bottom:2px;");
									elem.innerHTML = "<strong>Current Watches and Warnings</strong>"
									document.getElementById('warnbox').appendChild(elem);
									if (warnables.length < 1) {
										var elem = document.createElement("div");
										elem.innerHTML = "Currently no watches or warnings issued for selected area.";
										document.getElementById('warnbox').appendChild(elem);
									}
									for (var i = 0; i < warnables.length; i++ ) {
										var elem = document.createElement("div");
										elem.innerHTML = warnables[i];
										document.getElementById('warnbox').appendChild(elem);
									}
									var elem = document.createElement("div");
									elem.setAttribute("align", "center");
									elem.setAttribute("style", "padding-bottom:2px;");
									elem.innerHTML = "<strong>Current Conditions</strong>"
									document.getElementById('curbox').appendChild(elem);
									for (var i = 0; i < currents.length; i++ ) {
										var elem = document.createElement("div");
										elem.innerHTML = currents[i];
										document.getElementById('curbox').appendChild(elem);
									}
									
							}
							}
						
						var url = "http://www6.wrh.noaa.gov/mobile/point_data.php?lat=" + picklat + "&lon=" + picklong + "&FcstType=xml";
						x.open("GET", url, true);
						x.send(null);
						}
						
			    }
		</script>
		<script type="text/javascript">
		window.onload=function(){
		if(!NiftyCheck())
		    return;
			RoundedTop("div#skylightapp","transparent","#000000");
			RoundedBottom("div#skylightapp","transparent","#6699ff");
		}
		starttime();
		loadPagePrefs();
		</script>
    </head>
    
<body>
	<div id="skylightapp" style="width:775px;">
    <table width="775" border="0" cellspacing="0" cellpadding="0" class="page">
      <tr>
        <td>
        	<table width="100%" bgcolor="#000000" cellpadding="5">
        		<tr>
        			<td width="225" align="left" valign="top" onMouseDown="nativeWindow.startMove();"><img src="images/title.png" /><td>
        			<td align="right" valign="top">
						<form name="changeform">
						<input type="text" size="15" name="pickyplaces" />
						<input type="button" name="change" value="Change..." onClick="pageViaForm(this.form);" />
						<input type="button" name="save" value="Save" onClick="saveDefaultLocation();" />
						</form>		
        			</td>
					<td width="30" align="right" valign="top">
						<a href="#" onClick="nativeWindow.minimize();"><img src="images/minline.png" border="0" /></a>
						<a href="#" onClick="nativeWindow.close();"><img src="images/closex.png" border="0" /></a>
					</td>
        		</tr>
        	</table>
		</td>
      </tr>
      <tr>
        <td>
           	<div id="hiploader" style="display:none;background-color:#000033;" align="center">
            <br />
			<script type="text/javascript">
				var myProgBar = new progressBar(
					1,         //border thickness
					'#FFFFFF', //border colour
					'#0066CC', //background colour
					'#000066', 	 //bar colour
					200,       //width of bar (excluding border)
					10,        //height of bar (excluding border)
					1          //direction of progress: 1 = right, 2 = down, 3 = left, 4 = up
				);
			</script>
			<span style="color:#FFFFFF;">Loading...</span><br />
			</div>
			<div id="loaderror" style="padding-top:5px;display:none;background-color:#000033;color:#FFFFFF;" align="center">
				The internet could not be found.  Please connect to the internet and try again.<br /><br />
				If you are still recieving this error, our web server might be down, please try back soon.
			</div>
			<div id="welcomescreen" style="padding-top:5px;display:block;background-color:#000033;color:#FFFFFF;" align="center">
				<div style="font-size:14px;font-weight:bold;">WELCOME TO THE NWS SKYLIGHT FORECAST VIEWER</div>
				<div style="padding-top:5px;">
					Initiailizing Application...
				</div>
			</div>
			<div id="pickplace" align="center" style="color:#FFFFFF;background-color:#333333;"></div>
            <table id="hippy" align="center" width="100%" cellpadding="2" style="color:#FFFFFF;background-color:#000033;">
            	<tr id="ftop"></tr>
				<tr id="fbottom"></tr>
            </table>
			<div style="background:url(images/backing.png);background-repeat:repeatx;height:10px;"></div>
			<table id="extras" style="display:none;" cellpadding="4">
				<tr>
					<td width="50%" valign="top" align="left">
						<div align="center" style="padding-bottom:5px;"><strong>5-Day Detailed Forecast</strong></div>
						<div id="longcast" style="padding:3px;overflow:auto;height:300px;">
						</div>
					</td>
                    <td width="50%" valign="top">
                    <table width="100%" cellpadding="3">
					<tr><td id="warnbox" valign="top" align="center" colspan="2"></td></tr>
                    <tr>
                    	<td id="curbox" valign="top" align="center" width="50%"></td>
						<td valign="top" align="center" width="50%">Column Two</td>
					</tr>
					</table>
					</td>
				</tr>
			</table>
		</td>
      </tr>
    </table>
	</div>
	<form name="latlong">
		<input type="hidden" name="lats" id="lat" value="" />
		<input type="hidden" name="longs" id="long" value="" />
        <input type="hidden" name="place" id="place" value="" />
	</form>
</body>
</html>